import unittest
from unittest.mock import patch, mock_open
from io import StringIO
from main import print_file_contents  # 确保这里的导入路径是正确的

class TestPrintFileContents(unittest.TestCase):

    @patch('main.open', new_callable=mock_open, read_data='col1,col2\nrow1,row2')
    def test_print_file_contents_success(self, mock_file):
        # 测试文件内容正确打印
        mock_file_path = 'D:/py_workspace/demo-pjt/test.csv'
        expected_output = 'col1,col2\nrow1,row2'
        with patch('sys.stdout', new=StringIO()) as fake_output:
            print_file_contents(mock_file_path)
            self.assertEqual(fake_output.getvalue(), expected_output)

    @patch('main.open', mock_open())
    def test_file_not_found(self, mock_file):
        # 测试文件不存在的情况
        mock_file.side_effect = FileNotFoundError
        mock_file_path = 'D:/py_workspace/demo-pjt/nonexistent.csv'
        with patch('sys.stdout', new=StringIO()) as fake_output:
            print_file_contents(mock_file_path)
            self.assertIn("文件不存在", fake_output.getvalue())

    @patch('main.open', mock_open())
    def test_file_permission_error(self, mock_file):
        # 测试没有文件权限的情况
        mock_file.side_effect = PermissionError
        mock_file_path = 'D:/py_workspace/demo-pjt/forbidden.csv'
        with patch('sys.stdout', new=StringIO()) as fake_output:
            print_file_contents(mock_file_path)
            self.assertIn("没有权限读取文件", fake_output.getvalue())

    @patch('main.open', mock_open())
    def test_unexpected_error(self, mock_file):
        # 测试其他意外错误的情况
        mock_file.side_effect = ValueError("Unexpected error")
        mock_file_path = 'D:/py_workspace/demo-pjt/error.csv'
        with patch('sys.stdout', new=StringIO()) as fake_output:
            print_file_contents(mock_file_path)
            self.assertIn("打开文件时发生意外错误：ValueError", fake_output.getvalue())

if __name__ == '__main__':
    unittest.main()
